<template>
  <div class="app-container">
    <!--header头部区域-->
    <Header></Header>
    <!--循环渲染每一个商品信息-->
    <Goods v-for="item in list" :key="item.id" :id="item.id" :state="item.goods_state" :img="item.goods_img"
           :name="item.goods_name" :price="item.goods_price" :count="item.goods_count"
           @stateChange="getNewState"></Goods>
    <Footer :is-full="fullState" :total="amount" :all="total" @fullChange="getFullState"></Footer>
  </div>
</template>

<script>
import axios from 'axios'
import eventBus from "@/assets/js/eventBus";
import Header from "@/components/Header/Header";
import Goods from "@/components/Goods/Goods";
import Footer from "@/components/Footer/Footer";

export default {
  data() {
    return {
      list: [] //购物车列表数据
    }
  },
  components: {
    Header,
    Goods,
    Footer
  },
  computed: {
    //动态计算出全选的状态时是true还是false
    fullState() {
      return this.list.every(value => value.goods_state)
    },
    amount() { //已勾选商品总价格
      return this.list.filter(value => value.goods_state)
          .reduce((total, item) => (total += item.goods_price * item.goods_count), 0)
    },
    total() { //已勾选商品总数
      return this.list.filter(value => value.goods_state)
          .reduce((t, item) => (t += item.goods_count), 0)
    }
  },
  methods: {
    //初始化购物车数据
    async initCartList() {
      const {data: res} = await axios.get('https://www.escook.cn/api/cart')
      if (res.status === 200) {
        this.list = res.list
      }
    },
    getNewState(val) {
      this.list.some(value => {
        if (value.id === val.id) {
          value.goods_state = val.value
          return true
        }
      })
    },
    getFullState(val) {
      this.list.forEach(value => value.goods_state = val)
    }
  },
  created() {
    this.initCartList()
    eventBus.$on('share', val => {
      console.log(val)
      this.list.some(item => {
        if (item.id === val.id) {
          item.goods_count = val.value
          return true
        }
      })
    })
  },
}
</script>

<style lang="less" scoped>
.app-container {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
